# Create your views here.
import re

from django.conf import settings
from django.core.cache import cache
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.mixins import CreateModelMixin
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler

from lib import tx_sms
# from lib import tx_sms
from utils.response import APIResponse
from . import serializer, models
from .models import User
from .serializer import UserSerializer
from .throttle import SMSThrottle


class LoginView(ViewSet):
    def login(self, request, *args, **kwargs):
        ser = serializer.LoginSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(msg='登录成功', username=username, token=token)

    def mobile_login(self, request):
        # 逻辑写在序列化类中
        ser = serializer.MobileLoginSerializer(data=request.data)
        ser.is_valid(raise_exception=True)  # 执行序列化类字段自己的校验规则，局部钩子，全局钩子
        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(msg='登录成功', username=username, token=token)


class MobileView(ViewSet):
    @action(methods=['GET'], detail=False)
    def mobile(self, request):
        mobile = request.query_params.get('mobile')
        try:
            models.User.objects.get(mobile=mobile)
        except Exception:
            raise APIException('手机号不存在')
        return APIResponse(is_exisit=True)

    @action(methods=['GET'], detail=False, url_path='sms', throttle_classes=[SMSThrottle])
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if mobile and re.match(r'^1[3-9][0-9]{9}$', mobile):
            code = tx_sms.get_code()
            print(code)
            res = tx_sms.send_code(mobile, code)
            if res:
                cache.set(settings.CACHE_SMS % mobile, code)
                return APIResponse(msg='短信发送成功')
            else:
                raise APIException('短信发送失败')
        else:
            raise APIException('手机号不合法')


class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = User.objects.all()
    serializer_class = serializer.RegisterUserSerializer

    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)
        return APIResponse(msg='注册成功')


class Password(ViewSet):
    def post(self, request, *args, **kwargs):
        user = models.User.objects.filter(username=request.data['username']).first()
        if user and user.check_password(request.data['password']):
            user.set_password(request.data['password'])
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return APIResponse(msg='修改成功！', token=token)
        else:
            return APIResponse(code=101, msg='密码错误')


class UserInfo(ViewSet):
    def post(self, request, *args, **kwargs):
        res = models.User.objects.filter(username=request.data['username']).first()
        ser = UserSerializer(instance=res)
        return APIResponse(msg=ser.data)
